package com.manlitech.cloud.adminboot.notifier;
/*
 *Created by Intellij IDEA.
 *User:  Shensg
 *Date:  2021/3/1
 */

import com.alibaba.fastjson.JSONObject;
import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.notify.AbstractStatusChangeNotifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.Expression;
import org.springframework.expression.ParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import reactor.core.publisher.Mono;

import java.util.Map;

public class DingDingNotifier extends AbstractStatusChangeNotifier{

    private RestTemplate restTemplate = new RestTemplate();
    private String msgtype = "markdown";
    private String title = "服务告警";

    public DingDingNotifier(InstanceRepository repository) {
        super(repository);
    }

    @Override
    protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
        String serviceName = instance.getRegistration().getName();
        String serviceUrl = instance.getRegistration().getServiceUrl();
        String status = instance.getStatusInfo().getStatus();
        Map<String, Object> details = instance.getStatusInfo().getDetails();
        StringBuilder str = new StringBuilder();
        str.append("服务状态变更提醒 : [" + serviceName + "]");
        str.append("[服务地址]" + serviceUrl);
        str.append("[状态]" + status);
        str.append("[详情]" + details.toString());
        return Mono.fromRunnable(() -> {
            dingdingRobot(str.toString());
        });
    }

    public void dingdingRobot(String msg) {
        String url = "https://oapi.dingtalk.com/robot/send?access_token=bcd9e54764c2feb34db5af33f7146d846adbca1f35ce7e48d2da951dae31ac36";
        String requestJson = "" +
                "{\"msgtype\": \"text\",\"text\": {\"content\": \"warning :"+msg+"\"}}";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
        String answer = restTemplate.postForObject(url, entity, String.class);
        System.out.println(requestJson);
        System.out.println(answer);
    }


}
